import React, {Fragment, PureComponent} from 'react';
import {Icon,Button, Checkbox, DatePicker, Form, Input, InputNumber, Modal, Radio, Select, Steps,} from 'antd';
import DescriptionList from '@/components/DescriptionList';
import {nameMaxLength, remarkMaxLength, ruleP} from '@/utils/rule';
import moment from 'moment';
import {connect} from 'dva';

const {Description} = DescriptionList;
const FormItem = Form.Item;
const {Step} = Steps;
const {TextArea} = Input;
const {Option} = Select;
const {RangePicker} = DatePicker;
const CheckboxGroup = Checkbox.Group;
const dateFormat = 'YYYY/MM/DD';


@connect(({loading}) => ({
  submitting: loading.effects['privateFileModel/out'],
}))

/**
 * 个人文件，外发申请页面
 */
@Form.create()
class OutCreateForm extends PureComponent {
  static defaultProps = {
    handleOut: () => {
    },
    handleOutModalVisible: () => {
    },
    values: {},
  };

  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        id: '',
        dirName: '',
        applyTitle: '',
        applyReason: '',
        readTimes: '',
        filePwd: '',
        waterType: [],
        outType: 0,//目前只支持一体化外发
        sendType: '0',//目前只支持自己下载
        fileType:'',
        rightConfig: ['1'],
        startTime: null,
        endTime: null,
        endOpen: false,
      },
      currentStep: 0,

    };

    this.formLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 18},
    };
  }

  handleNext = currentStep => {

    const {form, handleOut, records, submitting} = this.props;
    const {formVals: oldValue} = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = {...oldValue, ...fieldsValue};
      this.setState(
        {
          formVals,
        },
        () => {
          if (currentStep < 3) {
            this.forward();
          } else {
            handleOut(formVals, records);
          }
        }
      );
    });
  };

  backward = () => {
    const {currentStep} = this.state;
    this.setState({
      currentStep: currentStep - 1,
    });
  };

  forward = () => {
    const {currentStep} = this.state;
    this.setState({
      currentStep: currentStep + 1,
    });
  };

  disabledStartDate = startTime => {
    const {endTime} = this.state;
    if (!startTime || !endTime) {
      return false;
    }
    return startTime.valueOf() > endTime.valueOf();
  };

  disabledEndDate = endTime => {
    const {startTime} = this.state;
    if (!endTime || !startTime) {
      return false;
    }
    if (endTime.valueOf() <= startTime.valueOf()) {
      return true;
    }
    if (endTime.valueOf() <= moment().valueOf()) {
      return true;
    }

    return false;
  };

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  };

  onStartChange = value => {
    this.onChange('startTime', value);
  };

  onEndChange = value => {
    this.onChange('endTime', value);
  };

  handleStartOpenChange = open => {
    if (!open) {
      this.setState({endOpen: true});
    }
  };

  handleEndOpenChange = open => {
    this.setState({endOpen: open});
  };

  onWaterOptionsChange = checkedList => {
    const {formVals,} = this.state;
    // {label: '明文水印', value: '1'},
    // {label: '屏幕水印', value: '2'},
    // {label: '暗水印', value: '3'},
    // {label: '打印水印', value: '4'},
  };

  //第一步 标题，理由
  renderFirstStep() {
    const {form, records, isAudit, orgAdmin, auditSetting,} = this.props;
    const {formVals,} = this.state;

    const fileNames = records.map((item) => {
      return item.dirName;
    }).join(",");
    let auditUsers = [];
    if (orgAdmin) {
      orgAdmin.forEach(item => {
        auditUsers.push(<Option key={item.userCode}>{item.userName}</Option>);
      });
    }

    let formArrays = [
      <FormItem key="fileName" {...this.formLayout} label="文件名称">
        {fileNames}
      </FormItem>,
      <FormItem key="name" {...this.formLayout} label="外发事项">
        {form.getFieldDecorator('applyTitle', {
          rules: [{required: true, message: '请输入外发事项！'}, {max: nameMaxLength()[0], message: nameMaxLength()[1]}],
          initialValue: formVals.applyTitle,
        })(<Input placeholder="请输入"/>)}
      </FormItem>,
      <FormItem key="desc" {...this.formLayout} label="外发理由">
        {form.getFieldDecorator('applyReason', {
          rules: [{required: true, message: '请输入至少五个字符的外发理由！', min: 5}, {
            max: remarkMaxLength()[0],
            message: remarkMaxLength()[1]
          }],
          initialValue: formVals.applyReason,
        })(<TextArea rows={4} placeholder="请输入至少五个字符"/>)}
      </FormItem>,
      ,
    ];


    if (auditSetting == 1) {
      let auditForm = <FormItem label="选择审批人" {...this.formLayout}>
        {form.getFieldDecorator('auditUserCode', {
          rules: [{required: true, message: '请选择审批人',},],
        })(
          <Select
            style={{width: '100%'}}
            placeholder="选择审批人"
          >
            {auditUsers}
          </Select>
        )}
      </FormItem>;
      formArrays.push(auditForm);
    }


    return formArrays;
  }

  //第二步 权限配置
  renderSeondStep() {
    const {form, records, authOptions, waterOptions} = this.props;
    // const AuthOptions = [
    //   {label: '只读', value: '1'},
    //   {label: '复制', value: '2'},
    //   {label: '编辑', value: '3'},
    //   {label: '另存', value: '4'},
    //   {label: '打印', value: '5'},
    //   {label: '截屏', value: '6'},
    //   {label: '逾期删除', value: '7'},
    //   {label: '明文还原', value: '8'},
    // ];
    const {formVals, startTime, endTime, endOpen} = this.state;


    return [
      <FormItem key="startTime" {...this.formLayout} label="开始时间">
        {form.getFieldDecorator('startTime', {
          rules: [{required: false, message: '请选择开始时间！'}],
          initialValue: formVals.startTime,
        })(
          <DatePicker
            style={{width: '100%'}}
            disabledDate={this.disabledStartDate}
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择开始时间"
            value={startTime}
            onChange={this.onStartChange}
            onOpenChange={this.handleStartOpenChange}


          />
        )}
      </FormItem>,
      <FormItem key="endTime" {...this.formLayout} label="结束时间">
        {form.getFieldDecorator('endTime', {
          rules: [{required: false, message: '请选择结束时间！'}],
          initialValue: formVals.endTime,
        })(
          <DatePicker
            style={{width: '100%'}}
            disabledDate={this.disabledEndDate}
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            value={endTime}
            placeholder="请选择结束时间"
            onChange={this.onEndChange}
            open={endOpen}
            onOpenChange={this.handleEndOpenChange}

          />
        )}
      </FormItem>,


      <FormItem key="readTimes" {...this.formLayout} label="阅读次数">
        {form.getFieldDecorator('readTimes', {
          rules: [{required: false, message: '请输入正确的阅读次数！'},],
          initialValue: formVals.readTimes,
        })(<InputNumber min={0} max={99999999} style={{width: '100%'}}/>)}
      </FormItem>,
      <FormItem key="filePwd" {...this.formLayout} label="打开密码">
        {form.getFieldDecorator('filePwd', {
          rules: [{required: false, message: '请输入密码！'},
            {pattern: new RegExp(ruleP(0)[0], 'g'), message: ruleP(0)[1]},
            {max: 20, message: "密码最长20位"}],
          initialValue: formVals.filePwd,
        })(<Input.Password placeholder="不输入则无打开密码"/>)}
      </FormItem>,
      <FormItem key="rightConfig" {...this.formLayout} label="权限控制">
        {form.getFieldDecorator('rightConfig', {
          rules: [{required: true, message: '编辑、只读权限请选择至少一个！'}],
          initialValue: formVals.rightConfig,
          normalize: (value, prevValue, allValues) => {
            // 选了只读，就不能选编辑
            let targetValues = value;
            const nowValues = prevValue || [];
            const selectValue = value.find(nv => nowValues.indexOf(nv) === -1);
            if (selectValue === '1') {
              targetValues = value.filter(x => x !== '3');
            } else if (selectValue === '3') {
              targetValues = value.filter(x => x !== '1');
            }

            return targetValues;
          }

        })(<CheckboxGroup options={authOptions}/>)}

      </FormItem>,

      <FormItem key="waterType" {...this.formLayout} label="水印控制">
        {form.getFieldDecorator('waterType', {
          rules: [{required: false, message: '请选择至少一个！'}],
          initialValue: formVals.waterType,
          normalize: (value, prevValue, allValues) => {
            // 1明文,3暗水印，两个只能存在一个
            let targetValues = value;
            const nowValues = prevValue || [];

            const selectValue = value.find(nv => nowValues.indexOf(nv) === -1);

            if (selectValue === '1') {
              targetValues = value.filter(x => x !== '3');
            } else if (selectValue === '3') {
              targetValues = value.filter(x => x !== '1');
            }

            return targetValues;
          },
        })(<CheckboxGroup options={waterOptions}/>)}
      </FormItem>];
  }

  //第三步 发送方式
  renderThirdStep() {
    const {form, records, authOptions, waterOptions} = this.props;
    return <Fragment>
      <FormItem key="sendType" {...this.formLayout} label="下载方式">
        {form.getFieldDecorator('sendType', {initialValue: 0})(
          <Radio.Group>
            <Radio value={0}>手动下载</Radio>
            <Radio value={1}>邮件下载</Radio>
          </Radio.Group>
        )}
      </FormItem>
      {form.getFieldValue('sendType') === 1 ? <FormItem key="emailAddr" {...this.formLayout} label="邮箱">
        {form.getFieldDecorator('emailAddr', {
          initialValue: '',
          rules: [{required: true, message: '邮箱不能为空'},
            {pattern: new RegExp(ruleP(9)[0], 'g'), message: ruleP(9)[1]}]
        })(
          <Input placeholder="请输入邮箱"/>)}
      </FormItem> : null}

      <FormItem key="fileType" {...this.formLayout} label="外发类型">
        {form.getFieldDecorator('fileType', {initialValue: 1})(
          <Radio.Group>
            <Radio value={1}>exe可执行文件</Radio>
            <Radio value={2}>文件包</Radio>
          </Radio.Group>
        )}
      </FormItem>
      <p style={{marginLeft:118}}><Icon type="info-circle" style={{color:'#faad14'}} />&nbsp;文件包：需要安装打开工具；exe可执行文件：双击可打开。</p>

    </Fragment>
  }

  //第四步 确认
  renderFourthStep() {
    const {form, records, authOptions, waterOptions} = this.props;
    //当前页面状态
    const {formVals,} = this.state;
    let rightConfig = formVals.rightConfig;
    let rightConfigText = "";
    if (rightConfig) {
      rightConfig.forEach(item => {
        authOptions.forEach(auth => {
          if (item == auth.value) {
            rightConfigText = rightConfigText + auth.label + ' ';
          }
        })
      })
    }

    let waterType = formVals.waterType;
    let waterTypeText = "";
    if (waterType) {
      waterType.forEach(item => {
        waterOptions.forEach(water => {
          if (item == water.value) {
            waterTypeText = waterTypeText + water.label + ' ';
          }
        })
      })
    }

    const fileNames = records.map((item) => {
      return item.dirName;
    }).join(",");
    return (
      <Form>
        <FormItem {...this.formLayout} label="文件名称">
          {fileNames}
        </FormItem>
        <FormItem {...this.formLayout} label="外发事项">
          {formVals.applyTitle}
        </FormItem>
        <FormItem {...this.formLayout} label="外发理由">
          {formVals.applyReason}
        </FormItem>
        <FormItem {...this.formLayout} label="阅读时限">
          开始时间：{formVals.startTime ? moment(formVals.startTime).format('YYYY-MM-DD HH:mm:ss') : "无限制"}，
          结束时间：{formVals.endTime ? moment(formVals.endTime).format('YYYY-MM-DD HH:mm:ss') : "无限制"}
        </FormItem>
        <FormItem {...this.formLayout} label="阅读次数">
          {formVals.readTimes ? formVals.readTimes : '无限制'}
        </FormItem>
        <FormItem {...this.formLayout} label="打开密码">
          {formVals.filePwd ? "有密码" : '无密码'}
        </FormItem>
        <FormItem {...this.formLayout} label="权限控制">
          {rightConfigText ? rightConfigText : '无'}
        </FormItem>
        <FormItem {...this.formLayout} label="水印控制">
          {waterTypeText ? waterTypeText : '无'}
        </FormItem>
        <FormItem {...this.formLayout} label="下载方式">
          {formVals.sendType ==0 ? '手动下载' : '邮件下载'}
        </FormItem>
        <FormItem {...this.formLayout} label="外发类型">
          {formVals.fileType ==2 ? '文件包' : 'exe可执行文件'}
        </FormItem>
      </Form>
    );
  }


  renderContent = (currentStep, formVals, values) => {
    const {form} = this.props;

    if (currentStep === 0) {
      return this.renderFirstStep();

    }
    if (currentStep === 1) {
      return this.renderSeondStep();

    }
    if (currentStep === 2) {
      return this.renderThirdStep();
    }
    if (currentStep === 3) {
      return this.renderFourthStep();
    }
    return null;


  };

  renderFooter = currentStep => {
    const {handleModalVisible, OutFormValues, submitting} = this.props;
    if (currentStep === 1 || currentStep === 2) {
      return [
        <Button key="back" style={{float: 'left'}} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleModalVisible(false)}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 3) {
      return [
        <Button key="back" style={{float: 'left'}} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleModalVisible(false, OutFormValues)}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)} loading={submitting}>
          完成
        </Button>,
      ];
    }
    return [
      <Button key="cancel" onClick={() => handleModalVisible(false, OutFormValues)}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
        下一步
      </Button>,
    ];
  };

  render() {
    const {handleModalVisible, modalVisible, values} = this.props;
    const {currentStep, formVals} = this.state;

    return (
      <Modal
        width={640}
        bodyStyle={{padding: '32px 40px 48px'}}
        destroyOnClose
        title="文件外发"
        visible={modalVisible}
        footer={this.renderFooter(currentStep)}
        onCancel={() => handleModalVisible()}
        afterClose={() => handleModalVisible()}
        maskClosable={false}
      >
        <Steps style={{marginBottom: 28}} size="small" current={currentStep}>
          <Step title="外发理由"/>
          <Step title="配置权限"/>
          <Step title="下载方式"/>
          <Step title="确认"/>
        </Steps>
        {this.renderContent(currentStep, formVals, values)}
      </Modal>
    );
  }
}

export default OutCreateForm;
